package cn.bugstack.design;

import java.util.concurrent.atomic.AtomicReference;

/**
 * CAS的忙等算法 实现单例模式
 * AtomicReference<V> 可以封装引用一个V实例，支持并发访问
 * 缺点:当然CAS也有一个缺点就是忙等，如果一直没有获取到将会处于死循环中。
 *
 * @author Hush.
 * @date 2022/9/8 17:54
 */
public class Singleton_06 {

    private static final AtomicReference<Singleton_06> INSTANCE = new AtomicReference<Singleton_06>();

    private static Singleton_06 instance;

    private Singleton_06() {
    }

    public static final Singleton_06 getInstance() {
        for (; ; ) {
            Singleton_06 instance = INSTANCE.get();
            if (null != instance) return instance;
            INSTANCE.compareAndSet(null, new Singleton_06());
            return INSTANCE.get();
        }
    }

}
